﻿using CoreShop.Model;
using CoreShop.Services;
using Sunny.UI;
using System;
using System.Windows.Forms;
using CoreShop.Library;
using SqlSugar.Extensions;
using System.Collections.Generic;
using CoreShop.Model.FromBody;
using Org.BouncyCastle.Asn1.Tsp;
using System.Linq;
using NPOI.Util;
using SqlSugar;
using static CoreShop.Model.FromBody.FPostData;
using System.Drawing;
using CoreShop.App.Units.Interface;
using Loading;
using System.Threading.Tasks;

namespace CoreShop.App
{
    public partial class frmFoodCategoryInfo : UIForm
    {
        corecmsfoodcategory foodcategory = new corecmsfoodcategory();
        public bool returnValue;
        private bool isDropClosed = false;
        OpaqueCommand cmd1 = new OpaqueCommand();
        public frmFoodCategoryInfo(corecmsfoodcategory _foodcategory)
        {
            InitializeComponent();
            parentSortName.TreeView.AfterSelect += new TreeViewEventHandler(parentSortName_AfterSelect);
            foodcategory = _foodcategory;
        }

        public frmFoodCategoryInfo()
        {
            InitializeComponent();
        }

        private async void GetItemSortCode()
        {
            try
            {
                cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
                long itemSortPid = 0;
                if (parentSortName.SelectedNode != null)
                    itemSortPid = CommFunc.ConvertToBigInt(parentSortName.SelectedNode.Tag);
                var resultModel = await FoodApiUtil.GetItemSortCode(itemSortPid);
                if (resultModel.code == 200)
                {
                    spuNumber.Text = resultModel.msg;
                }
            }
            catch (Exception)
            {
                //throw;
            }
            finally { cmd1.HideOpaqueLayer(); }
        }

        private void parentSortName_AfterSelect(object sender, TreeViewEventArgs e)
        {
            parentSortName.SelectedNode = e.Node;            
            parentSortName.Text = e.Node.Text;
            if (isDropClosed) SendKeys.Send("{ESC}");//第一次选择自动关闭了，所以加这一句。
            isDropClosed = true;
        }

        private bool CheckData1()
        {
            if (string.IsNullOrEmpty(spuNumber.Text))
            {
                UIMessageBox.Show("请输入或生成分类编码", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            if (string.IsNullOrEmpty(itemSortName.Text))
            {
                UIMessageBox.Show("请输入名称", "提示", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            return true;
        }

        private void FrmEditInputs_Load(object sender, EventArgs e)
        {
            ControlsDataBinding.DataBind(foodcategory, this, DataSourceUpdateMode.OnPropertyChanged);

            LoadFoodCategroy();
        }

        private void LoadFoodCategroy()
        {
            List<FMLongId> typeList = new corecmsfoodServices().AsQueryable()
                .GroupBy(t => new { t.foodTypeId})
                .Select(t => new FMLongId { id = t.foodTypeId })
                .With(SqlWith.NoLock).ToList();

            parentSortName.Nodes.Clear();
            List<corecmsfoodcategory> lstSource = new corecmsfoodcategoryServices().AsQueryable()
                .Where(p => p.isDelete != true && p.tenantId == AppConstVars.sysStore.corpId).ToList();
            var parents = lstSource.Where(p => p.parentId == 0).ToList();
            TreeNode treeNode1 = null;
            treeNode1 = new TreeNode("top0");
            treeNode1.Tag = "0";
            parentSortName.Nodes.Add("<无>");
            parentSortName.SelectedNode = treeNode1;
            parentSortName.Text = "<无>";
            foreach (var item in parents)
            {
                var typeItem = typeList.Find(p => p.id == item.id);
                if (typeItem != null) continue;//下面已有商品，不能添加该分类
                treeNode1 = new TreeNode(item.name);
                treeNode1.Tag = item.id.ToString();
                parentSortName.Nodes.Add(treeNode1);
                var childs = lstSource.Where(p => p.parentId == item.id).ToList();
                foreach (var child in childs)
                {
                    var typeItem1 = typeList.Find(p => p.id == child.id);
                    if (typeItem1 != null) continue;//下面已有商品，不能添加该分类
                    TreeNode treeNode2 = new TreeNode(child.name);                    
                    treeNode2.Tag = child.id.ToString();
                    treeNode1.Nodes.Add(treeNode2);
                }
            }
            parentSortName.Nodes[0].Expand();
        }

        private async void DoCreate()
        {
            try
            {
                string itemSortPid = "0";
                if (parentSortName.SelectedNode != null)
                    itemSortPid = CommFunc.ConvertToBigInt(parentSortName.SelectedNode.Tag).ToString();
                InsertPdtItemSortModel InsertSortInfo = new InsertPdtItemSortModel();
                InsertSortInfo.itemSortCode = spuNumber.Text;
                InsertSortInfo.itemSortName = itemSortName.Text;
                InsertSortInfo.itemSortPid = itemSortPid;
                InsertSortInfo.canPos = 0;
                InsertSortInfo.canParentPos = 0;
                InsertSortInfo.status = 0;
                InsertSortInfo.orderNum = 0;
                var resultModel = await FoodApiUtil.SaveProductType(InsertSortInfo);
                if (resultModel.status)
                {
                    DialogResult = DialogResult.OK;
                }
                else
                {
                    MessageBox.Show(resultModel.msg);
                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void SetControlClear()
        {
            foreach (Control Ctrol in this.Controls)
            {
                if (Ctrol is Sunny.UI.UITextBox)
                {
                    Ctrol.Text = "";
                }
            }
            foodcategory.id = 0;
        }


        private void btnOk_Click(object sender, EventArgs e)
        {
            if (!CheckData1()) return;
            try
            {
                cmd1.ShowOpaqueLayer(pnl_Form, 125, true);
                DoCreate();              
            }
            catch (Exception)
            {
                throw;
            }
            finally { cmd1.HideOpaqueLayer(); }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private bool DoEdit()
        {            
            return false;
        }

        private void frmFoodCategoryInfo_FormClosed(object sender, FormClosedEventArgs e)
        {
            HideWaitForm();
        }

        private void btnGetCode_Click(object sender, EventArgs e)
        {
            GetItemSortCode();
        }

        private void parentSortName_TextChanged(object sender, EventArgs e)
        {
            GetItemSortCode();
        }

        private void parentSortName_NodeSelected(object sender, TreeNode node)
        {
            btnGetCode_Click(null, null);
        }
    }
}